package com.lanou.web.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.lanou.config.AliPayConfig;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/pay")
public class PayController {

    @PostMapping("/ali")
    public String aliPay(String orderId) {
        double total = 19.9;
        String subject = "测试商品123123";

        AlipayClient alipayClient = new DefaultAlipayClient(AliPayConfig.gateway, AliPayConfig.appId,
                AliPayConfig.sign, "json", AliPayConfig.charset, AliPayConfig.aliPayPublicKey, AliPayConfig.signType);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();

        String bizContent = "{"
                + "\"out_trade_no\":\"" + orderId + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\","
                + "\"total_amount\":" + total + ","
                + "\"subject\":\"" + subject + "\""
                + "}";

        request.setBizContent(bizContent);
        request.setReturnUrl("http://www.baidu.com");
        String payUrl = null;
        try {
//            response = alipayClient.pageExecute(request);
            payUrl = alipayClient.pageExecute(request, "GET").getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        return "redirect:" + payUrl;
    }
}
